#!/usr/bin/env python3.10
# -*- encoding: utf-8 -*-
'''
@File    :   rule.py
@Time    :   2023/11/17 11:32:59
@Author  :   windstarry 
@Version :   1.0
'''
# here put the import lib
from typing import List
from ninja import Router, Schema
from casbin_adapter.models import CasbinRule
from casbin_adapter.enforcer import enforcer

router = Router()

  
class RuleSchemaIn(Schema):
  role: str
  path: str
  method: str

  
class RuleListSchemaIn(Schema):
  role: str
  list: List[RuleSchemaIn]

  
@router.get("/rule/{code}")
def get_rule(request, code: str):
  all = enforcer.get_filtered_policy(0, code)
  return all

  
@router.post("/rule")
def add_rule(request, rules: RuleListSchemaIn):
  enforcer.delete_permissions_for_user(rules.role)
  if rules.list.__len__ != 0:
    for rule in rules.list:
      #new_casbin_rule = CasbinRule()
      #new_casbin_rule.ptype = "p"
      #new_casbin_rule.v0 = rule.role
      #new_casbin_rule.v1 = rule.path
      #new_casbin_rule.v2 = rule.method
      #new_casbin_rule.v3 = rule.id
      #new_casbin_rule.save()
      enforcer.add_named_policy("p", rule.role, rule.path, rule.method)
  return {"msg": "添加规则成功"}